package com.zhs.xyzsdk.views;

import java.util.ArrayList;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.zhs.javacc.SimpleNode;
import com.zhs.javacc.Token;
import com.zhs.type.Method;
import com.zhs.type.Type;
import com.zhs.type.TypeChecker;
import com.zhs.type.Variable;
import com.zhs.xyzsdk.editors.XYZEditor;
import com.zhs.xyzsdk.editors.token.TokenManager;

/**
 * This sample class demonstrates how to plug-in a new workbench view. The view
 * shows data obtained from the model. The sample creates a dummy model on the
 * fly, but a real implementation would connect to the model available either in
 * this or another plug-in (e.g. the workspace). The view is connected to the
 * model using a content provider.
 * <p>
 * The view uses a label provider to define how model objects should be
 * presented in the view. Each view can present the same model objects using
 * different labels and icons, if needed. Alternatively, a single label provider
 * can be shared between views in order to ensure that objects of the same type
 * are presented in the same way everywhere.
 * <p>
 */

public class TreeView extends ViewPart {
	private static TreeViewer viewer;
	private static Object beginInput;
	private DrillDownAdapter drillDownAdapter;
	private Action action1;
	private Action action2;
	private Action action3;
	private Action doubleClickAction;
	private SimpleNode invisibleRoot;

	/*
	 * The content provider class is responsible for providing objects to the
	 * view. It can wrap existing objects in adapters or simply return objects
	 * as-is. These objects may be sensitive to the current input of the view,
	 * or ignore it and always show the same content (like Task List, for
	 * example).
	 */

	class TreeObject implements IAdaptable {
		private String name;
		private TreeParent parent;

		public TreeObject(String name) {
			this.name = name;
		}

		public String getName() {
			return name;
		}

		public void setParent(TreeParent parent) {
			this.parent = parent;
		}

		public TreeParent getParent() {
			return parent;
		}

		public String toString() {
			return getName();
		}

		public Object getAdapter(Class key) {
			return null;
		}
	}

	class TreeParent extends TreeObject {
		private ArrayList children;

		public TreeParent(String name) {
			super(name);
			children = new ArrayList();
		}

		public void addChild(TreeObject child) {
			children.add(child);
			child.setParent(this);
		}

		public void removeChild(TreeObject child) {
			children.remove(child);
			child.setParent(null);
		}

		public TreeObject[] getChildren() {
			return (TreeObject[]) children.toArray(new TreeObject[children
					.size()]);
		}

		public boolean hasChildren() {
			return children.size() > 0;
		}
	}

	class ViewContentProvider implements IStructuredContentProvider,
			ITreeContentProvider {

		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
			viewer = (TreeViewer) v;
			if (newInput instanceof SimpleNode) {
				invisibleRoot = (SimpleNode) newInput;
			}
			// refreshing the contents of the tree according to the value of
			// newInput.
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					// WeightCalculator.calcWeight(invisibleRoot);
					viewer.refresh(true);
				}
			});

		}

		public void dispose() {
		}

		public Object[] getElements(Object parent) {
			System.out.println("getElements");
			if (parent.equals(getViewSite())) {
				// initialize();
				return getChildren(invisibleRoot);
			}
			return getChildren(parent);
		}

		public Object getParent(Object child) {
			if (child instanceof SimpleNode) {
				return ((SimpleNode) child).jjtGetParent();
			}
			return null;
		}

		public Object[] getChildren(Object parent) {
			if (parent instanceof SimpleNode) {
				SimpleNode p = (SimpleNode) parent;
				SimpleNode[] children = new SimpleNode[p.jjtGetNumChildren()];
				for (int i = 0; i < children.length; i++) {
					children[i] = (SimpleNode) p.jjtGetChild(i);
				}
				return children;
			}
			return new Object[0];
		}

		public boolean hasChildren(Object parent) {
			if (parent instanceof SimpleNode)
				return ((SimpleNode) parent).jjtGetNumChildren() > 0;
			return false;
		}

		/*
		 * We will set up a dummy model to initialize tree heararchy. In a real
		 * code, you will connect to a real model and expose its hierarchy.
		 */
		private void initialize() {
			// TreeObject to1 = new TreeObject("Leaf 1");
			// TreeObject to2 = new TreeObject("Leaf 2");
			// TreeObject to3 = new TreeObject("Leaf 3");
			// TreeParent p1 = new TreeParent("Parent 1");
			// p1.addChild(to1);
			// p1.addChild(to2);
			// p1.addChild(to3);
			//
			// TreeObject to4 = new TreeObject("Leaf 4");
			// TreeParent p2 = new TreeParent("Parent 2");
			// p2.addChild(to4);
			//
			// TreeParent root = new TreeParent("Root");
			// root.addChild(p1);
			// root.addChild(p2);
			//
			// invisibleRoot = new TreeParent("");
			// invisibleRoot.addChild(root);
		}
	}

	class ViewLabelProvider extends LabelProvider {

		public String getText(Object obj) {
			if (obj instanceof SimpleNode) {
				StringBuffer label = new StringBuffer(obj.toString());
				// Object value = ((SimpleNode) obj).jjtGetValue();
				Token token = ((SimpleNode) obj).jjtGetFirstToken();
				if (token != null) {
					if (((SimpleNode) obj).jjtGetLastToken().next == token) {
						label.append(" <EPSILON>");
					} else {
						label.append(" \"");
						label.append(token.image);
						if (((SimpleNode) obj).jjtGetFirstToken() != ((SimpleNode) obj)
								.jjtGetLastToken()) {
							label.append("...");
						}
						label.append("\"");
					}
				}
				// if (value != null) {
				// label.append(" weight: " + value.toString());
				// }
				return label.toString();
			}
			return obj.toString();
		}

		public Image getImage(Object obj) {
			String type = "";
			if (obj instanceof SimpleNode) {
				type = obj.toString();
			}
			String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
			if (type.endsWith("Declaration")) {
				imageKey = ISharedImages.IMG_OBJ_FOLDER;
			}
			if (type.endsWith("MainClass")) {
				imageKey = ISharedImages.IMG_OBJ_FOLDER;
			}
			if (type.endsWith("Statement")) {
				imageKey = ISharedImages.IMG_OBJS_INFO_TSK;
			}
			if (type.endsWith("Literal")) {
				imageKey = ISharedImages.IMG_OBJ_FILE;
			}
			return PlatformUI.getWorkbench().getSharedImages().getImage(
					imageKey);
		}
	}

	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public TreeView() {
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		// viewer.setSorter(new NameSorter());
		if (beginInput == null) {
			viewer.setInput(getViewSite());
		} else {
			viewer.setInput(beginInput);
		}
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				TreeView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
		manager.add(new Separator());
		manager.add(action3);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(action1);
		manager.add(action2);
		manager.add(action3);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
		manager.add(action3);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				viewer.collapseAll();
			}
		};
		action1.setText("Collapse All");
		action1.setToolTipText("Collapse all");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
				.getImageDescriptor(ISharedImages.IMG_TOOL_BACK));

		action2 = new Action() {
			public void run() {
				// showMessage("Action 2 executed");
				viewer.expandAll();
			}
		};
		action2.setText("Expand All");
		action2.setToolTipText("Expand the entire tree");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
				.getImageDescriptor(ISharedImages.IMG_TOOL_FORWARD));

		action3 = new Action() {
			public void run() {
				StringBuffer sb = new StringBuffer();
				for (Type t : Type.getAllTypes()) {
					sb.append("In class " + t.getTypeName() + ":\n");
					for (Variable var : t.getScope().getVariables().values()) {
						sb.append("\tVariable name: ");
						sb.append(var.getVarName());
						sb.append("\t\ttype: ");
						sb.append(var.getTypeName());
						sb.append("\n");
					}
					for (Method m : t.getExclusiveMethods()) {
						sb.append("\tIn method " + m.getMethodName() + ":\n");
						for (Variable var : m.getDeclaredVariables()) {
							sb.append("\t\tVariable name: ");
							sb.append(var.getVarName());
							sb.append("\t\ttype: ");
							sb.append(var.getTypeName());
							sb.append("\n");
						}
					}
				}
				showMessage(sb.toString());
			}
		};
		action3.setText("List all variables");
		action3.setToolTipText("List all viables");
		action3.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
				.getImageDescriptor(ISharedImages.IMG_TOOL_UP));

		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection) selection)
						.getFirstElement();
				if (obj instanceof SimpleNode) {
					Token first = ((SimpleNode) obj).jjtGetFirstToken();
					Token last = ((SimpleNode) obj).jjtGetLastToken();
					int offset = TokenManager.getOffset(first.beginLine,
							first.beginColumn, XYZEditor.getDoc());
					int length;
					if (last.next != first) {
						length = TokenManager.getOffset(last.endLine,
								last.endColumn, XYZEditor.getDoc())
								- offset;
					} else {
						length = 1;
					}
					XYZEditor.setHighlight(offset, length, true);
				} else
					showMessage("Double-click detected on " + obj.toString());
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}

	private void showMessage(String message) {
		MessageDialog.openInformation(viewer.getControl().getShell(),
				"Tree View", message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}

	public static void refresh(final SimpleNode root) {
		new Thread(new Runnable() {
			public void run() {
				if(root == null) return;
				new TypeChecker().addTypes(root);
			}
		}).start();
		if (viewer == null) {
			beginInput = root;
		} else {
			viewer.setInput(root);
		}
	}

}